package com.googlecode.continuity.plugin.syntaxhighlight.client;

import com.google.gwt.core.client.JavaScriptObject;

/**
 * SelectableLinesHighlighter
 *
 * @author Peter Schmitt <aragos@aragos.de>
 */
public class SelectableLinesHighlighter {
  private String language;
  private JavaScriptObject highlighter;

  public SelectableLinesHighlighter(String language) throws UnsupportedLanguageException {
    this.language = language;
    highlighter = createHighlighter(language);
    if (highlighter == null) {
      throw new UnsupportedLanguageException("Language [" + language + "] is not supported by Highlighter." +
          "(Hint: Check your language file imports.)");
    }
  }

  private native JavaScriptObject createHighlighter(String language) /*-{
    var registered = @com.googlecode.continuity.plugin.syntaxhighlight.client.HighlightInit::registered;
    if(registered[language] == null) {
      return null;
    }
    return new $wnd.dp.sh.Brushes[registered[language]]();
  }-*/;

  public String[] highlight(String code, boolean tabsToSpaces) {
    String markup = getHighlightedCode(code, tabsToSpaces);
    return removeBreaks(markup).split("\\n");
  }

  private native String getHighlightedCode(String code, boolean tabsToSpaces) /*-{
    return this.@com.googlecode.continuity.plugin.syntaxhighlight.client.SelectableLinesHighlighter::highlighter.
        Highlight(code, tabsToSpaces);
  }-*/;

  private native String removeBreaks(String code) /*-{
    return code.replace(/<(br)\/?>/gi, '\n');
  }-*/;
}
